home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 5509 < prev    next >
Encoding:
Text File  |  1996-08-05  |  2.1 KB  |  93 lines

  1. Path: qualcomm.com!usenet
  2. From: nabbasi@qualcomm.com (Nasser Abbasi)
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: Derived Class Function ?
  5. Date: 5 Feb 1996 06:40:39 GMT
  6. Organization: QUALCOMM
  7. Message-ID: <4f48p7$rpq@qualcomm.com>
  8. References: <toddosDM9o9r.Ezw@netcom.com>
  9. NNTP-Posting-Host: nabbasi.qualcomm.com
  10. Mime-Version: 1.0
  11. X-Newsreader: WinVN 0.93.14
  12.  
  13. In article <toddosDM9o9r.Ezw@netcom.com>, toddos@netcom.com says...
  14. >
  15. >Does anyone know a way to tell in a base class if a derived class
  16. >overrides a virtual function without calling the function? In other
  17. >words, I do not want to even call the base class implementation of a
  18. >function if a derived class does NOT override it. Thanks.
  19. >
  20. >Todd
  21. >
  22.  
  23. Interesting question. May be you can try something like this quick hack
  24. below. Probably there is a more elegent way of doing 
  25. it.
  26.  
  27. Nasser
  28.  
  29. ----------------------------- cut here -------------------------------
  30.  
  31. #include <iostream.h>
  32.  
  33. //
  34. // example how to tell in base class if a virtual function
  35. // in base class has been ovverriden. If so then call it, else
  36. // do not.  (or di whatever you want)
  37. //
  38. // Use flag at construction time to indicate if a base class has
  39. // been extended by another class.
  40. //
  41. // Nasser Abbasi
  42. //
  43.  
  44. #define true 1
  45. #define false 0
  46.  
  47. typedef unsigned short int bool;
  48.  
  49. class base
  50. {
  51.   public:    
  52.     base(bool flag=false) : is_override (flag) {}
  53.     virtual void foo() { cout<< "in base::foo() \n"; }
  54.  
  55.     void test() {
  56.                   // do a test to see if we should call a virtual
  57.                   // function or not. If it has been overriden, call it
  58.                   // else do not
  59.                   if(is_override)
  60.                      foo();
  61.                   else
  62.                      return;
  63.                  }
  64.   private:
  65.     bool is_override;
  66. };
  67.  
  68. class derived: public base
  69. {
  70.   public:    
  71.     derived(): base(true) {}
  72.     void foo() { cout<< "in derived::foo() \n"; }
  73. };
  74.  
  75. main()
  76. {
  77. base obj;
  78. derived obj_1;
  79.  
  80. cout<<"befor calling obj.test()\n";
  81. obj.test();    // this will NOT call base::foo() since it is not 
  82. overriden
  83.  
  84. cout<<"befor callling obj_1.test()\n";
  85. obj_1.test();  // this WILL call derived::foo() since it is overriden
  86.  
  87. return 1;
  88. }
  89.  
  90.  
  91. 
  92.  
  93.